#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：pythonProject2 
@File    ：hero_exe_update.py
@Author  ：beibei
@Date    ：2024/3/26 4:25 PM 
'''
import requests
import os
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm


def fetch_hero_list():
    url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?v=20'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        return data.get('hero', [])
    else:
        return []


def fetch_hero_skins(hero_id):
    url = f'https://game.gtimg.cn/images/lol/act/img/js/hero/{hero_id}.js'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        return data.get('skins', [])
    else:
        return []


def save_skin_image(skin_info):
    skin_id, skin_name, hero_name = skin_info
    url = f'https://game.gtimg.cn/images/lol/act/img/skin/big{skin_id}.jpg'
    try:
        response = requests.get(url)
        response.raise_for_status()
        img_data = response.content
        # 切换到home目录
        home_directory = os.path.expanduser('~')
        save_path = os.path.join(home_directory, 'Desktop', 'lol_skins', hero_name)
        os.makedirs(save_path, exist_ok=True)
        with open(os.path.join(save_path, f'{skin_name}.jpg'), 'wb') as file:
            file.write(img_data)
    except Exception as e:
        print(f'Error saving {skin_name} for {hero_name}: {e}')


def download_hero_skins(hero):
    hero_id, hero_name = hero['heroId'], hero['name']
    skins = fetch_hero_skins(hero_id)
    skin_infos = []
    for skin in skins:
        if skin['name'] != 'default':
            # 创建一个包含skinId, skin name和hero name的元组
            skin_info = (skin['skinId'], skin['name'], hero_name)
            # 将这个元组添加到skin_infos列表中
            skin_infos.append(skin_info)

    return skin_infos


def main():
    heroes = fetch_hero_list()
    all_skins = []
    with ThreadPoolExecutor() as executor:
        # 下载每个英雄的皮肤信息
        for skins in executor.map(download_hero_skins, heroes):
            all_skins.extend(skins)

    # 并发下载所有皮肤图片
    with ThreadPoolExecutor() as executor:
        # 创建一个由tqdm包装的迭代器，用于显示进度条
        progress_bar = tqdm(executor.map(save_skin_image, all_skins), total=len(all_skins), desc="Downloading Skins")

        # 遍历迭代器以执行所有任务，并触发进度条更新
        for _ in progress_bar:
            pass


if __name__ == '__main__':
    main()
